<template>
	<view class="chat-container">
		<!-- 未登录提示 -->
		<view v-if="!isLoggedIn" class="login-tip">
			<text>登录后查看消息</text>
			<button @tap="goToLogin" class="login-btn">去登录</button>
		</view>

		<!-- 已登录内容 -->
		<block v-else>
			<!-- 头部返回 + 用户名 -->
			<view class="chat-header">
				<view @click="goBack" class="back-button">返回</view>
				<text class="chat-name">{{ chatName }}</text>
			</view>

			<!-- 商品信息卡片 - 固定在顶部 -->
			<view v-if="chatInfo && chatInfo.productInfo" class="product-card-container">
				<view class="product-card">
					<image :src="chatInfo.productInfo.img" class="product-image" mode="aspectFill" />
					<view class="product-info">
						<text class="product-name">{{ chatInfo.productInfo.name }}</text>
						<text class="product-price">¥{{ chatInfo.productInfo.price }}</text>
						<button class="order-btn" @tap="placeOrder" @click="dian">立即下单</button>
					</view>
				</view>
			</view>

			<!-- 聊天记录 -->
			<scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true"
				@scrolltoupper="loadMoreMessages">
				<!-- 消息列表 -->
				<view v-for="(message, index) in messageList" :key="index"
					:class="['message-item', message.isSelf ? 'message-self' : 'message-other']">
					<!-- 对方头像 -->
					<image v-if="!message.isSelf" :src="chatInfo.sellerAvatar || '/static/default-avatar.png'"
						class="avatar left-avatar" />

					<!-- 消息内容 -->
					<view class="message-content">
						<!-- 消息时间 -->
						<view class="message-time">{{ formatTime(message.time) }}</view>
						<!-- 消息文本或图片 -->
						<view class="message-bubble">
							<text v-if="message.type === 'text'" class="text-message">{{ message.content }}</text>
							<image v-else-if="message.type === 'image'" :src="message.url" class="image-message"
								mode="widthFix" @tap="previewImage(message.url)" />
						</view>
					</view>

					<!-- 自己的头像 -->
					<image v-if="message.isSelf" :src="userInfo.avatarUrl || '/static/default-avatar.png'"
						class="avatar right-avatar" />
				</view>
			</scroll-view>

			<!-- 输入框区域 -->
			<view class="input-area">
				<view class="input-container">
					<textarea v-model="messageText" class="message-input" :adjust-position="false" :cursor-spacing="20"
						:show-confirm-bar="false" :fixed="true" auto-height placeholder="输入消息..." />
					<view class="button-group">
						<view @tap="chooseImage" class="icon-button">
							<text class="icon">图片</text>
						</view>
						<view @tap="sendMessage" class="send-button" :class="{ 'active': messageText.trim() }">
							发送
						</view>
					</view>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	import messageApi from '@/utils/api.js';

	export default {
		name: "ChatDetail",
		data() {
			return {
				partnerId: null,
				chatName: '',
				messageList: [],
				messageText: '',
				scrollTop: 0,
				page: 1,
				loading: false,
				hasMore: true,
				size: 20,
				chatInfo: {
					sellerId: '',
					sellerName: '',
					sellerAvatar: '',
					productInfo: null
				},
				userInfo: null,
				isLoggedIn: false,
				baseUrl: process.env.VUE_APP_BASE_API || ''
			};
		},
		onShow() {
			// 每次显示页面时检查登录状态
			this.checkLoginStatus();
		},
		onLoad(options) {
			this.userInfo = uni.getStorageSync('userInfo');
			this.checkLoginStatus();

			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('chatInfo', (data) => {
				console.log('接收到的聊天信息:', data);
				// 设置 partnerId
				this.partnerId = data.sellerId;

				// 更新聊天信息
				this.chatInfo = {
					sellerId: data.sellerId,
					sellerName: data.sellerName || '',
					sellerAvatar: data.sellerAvatar || '/static/default-avatar.png',
					productInfo: data.productInfo || null // 直接使用传递过来的商品信息
				};

				// 设置聊天名称
				this.chatName = data.sellerName || '';

				// 重置消息列表和分页
				this.page = 1;
				this.messageList = [];

				// 加载历史消息
				this.loadHistoryMessages();

				// 如果没有商品信息，则尝试从服务器获取
				if (!this.chatInfo.productInfo) {
					this.loadChatDetail();
				}
			});
		},
		onUnload() {
			// 重置分页状态
			this.page = 1;
			this.messageList = [];
			this.hasMore = true;
		},
		methods: {
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				const userInfo = uni.getStorageSync('userInfo');
				this.isLoggedIn = !!(token && userInfo);
				this.userInfo = userInfo;

				// 如果已登录且有卖家ID，加载消息
				if (this.isLoggedIn && this.chatInfo?.sellerId) {
					this.loadHistoryMessages();
				}
			},

			goToLogin() {
				// 保存当前页面状态
				if (this.chatInfo) {
					uni.setStorageSync('lastChatInfo', this.chatInfo);
				}

				uni.navigateTo({
					url: '/pages/Information/login/login',
					fail: (err) => {
						console.error('跳转登录页失败:', err);
						uni.showToast({
							title: '跳转失败',
							icon: 'none'
						});
					}
				});
			},
			placeOrder() {
				uni.showModal({
					title: '确认下单',
					content: `是否确认购买 ${this.chatInfo.productInfo.name}？`,
					success: (res) => {
						if (res.confirm) {
							// 发起下单请求
							uni.request({
								url: this.baseUrl + '/wx/order/submit',
								method: 'POST',
								header: {
									'content-type': 'application/json',
									'X-Token': uni.getStorageSync('token')
								},
								data: {
									productId: this.chatInfo.productInfo.id,
									sellerId: this.chatInfo.sellerId,
									price: this.chatInfo.productInfo.price
								},
								success: (response) => {
									if (response.statusCode === 200 && response.data.errno === 0) {
										const orderId = response.data.data;
										// 下单成功后，发起支付
										this.requestPayment(orderId);
									} else {
										uni.showToast({
											title: response.data.errmsg || '下单失败',
											icon: 'none'
										});
									}
								},
								fail: (error) => {
									console.error('下单失败:', error);
									uni.showToast({
										title: '下单失败',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},
			requestPayment(orderId) {
				// 获取支付参数
				uni.request({
					url: this.baseUrl + '/wx/order/prepay',
					method: 'POST',
					header: {
						'content-type': 'application/json',
						'X-Token': uni.getStorageSync('token')
					},
					data: {
						orderId: orderId
					},
					success: (response) => {
						if (response.statusCode === 200 && response.data.errno === 0) {
							const payParams = response.data.data;
							// 调起支付
							uni.requestPayment({
								provider: 'wxpay',
								...payParams,
								success: (res) => {
									uni.showToast({
										title: '支付成功',
										icon: 'success'
									});
									// 支付成功后跳转到订单详情页
									uni.navigateTo({
										url: `/pages/order/detail?orderId=${orderId}`
									});
								},
								fail: (err) => {
									console.error('支付失败:', err);
									// 支付失败也跳转到订单详情页，让用户可以重新支付
									uni.navigateTo({
										url: `/pages/order/detail?orderId=${orderId}&payStatus=fail`
									});
								}
							});
						} else {
							uni.showToast({
								title: response.data.errmsg || '获取支付参数失败',
								icon: 'none'
							});
						}
					},
					fail: (error) => {
						console.error('获取支付参数失败:', error);
						uni.showToast({
							title: '获取支付参数失败',
							icon: 'none'
						});
					}
				});
			},
			goBack() {
				uni.navigateBack();
			},
			async loadHistoryMessages() {
				if (!this.chatInfo?.sellerId || !this.userInfo?.id) {
					console.log('缺少必要参数:', {
						sellerId: this.chatInfo?.sellerId,
						userId: this.userInfo?.id
					});
					return;
				}

				try {
					const token = uni.getStorageSync('token');
					if (!token) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}

					const res = await messageApi.getHistory(
						this.chatInfo.sellerId,
						this.page,
						this.size
					);

					if (res.data.errno === 0) {
						const currentUserId = parseInt(this.userInfo.id);
						const newMessages = res.data.data.map(msg => {
							const senderId = parseInt(msg.senderId);
							const isSelf = senderId === currentUserId;

							return {
								id: msg.id,
								content: msg.content,
								type: msg.type || 'text',
								time: msg.createTime,
								senderId: senderId,
								receiverId: parseInt(msg.receiverId),
								isSelf: isSelf,
								url: msg.type === 'image' ? msg.content : undefined
							};
						});

						// 按时间排序
						newMessages.sort((a, b) => new Date(a.time) - new Date(b.time));

						if (this.page === 1) {
							this.messageList = newMessages;
						} else {
							// 合并消息并去重
							const uniqueMessages = [...this.messageList];
							newMessages.forEach(newMsg => {
								if (!uniqueMessages.some(msg => msg.id === newMsg.id)) {
									uniqueMessages.push(newMsg);
								}
							});
							this.messageList = uniqueMessages;
						}

						this.hasMore = newMessages.length >= this.size;
						this.page++;

						if (this.page === 2) {
							this.scrollToBottom();
						}
					} else if (res.data.errno === 501) {
						this.isLoggedIn = false;
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
					} else {
						throw new Error(res.data.errmsg || '加载消息失败');
					}
				} catch (error) {
					console.error('加载历史消息失败:', error);
					uni.showToast({
						title: error.message || '加载消息失败',
						icon: 'none'
					});
				}
			},
			async sendMessage() {
				try {
					if (!this.messageText.trim()) return;

					const messageData = {
						toUserId: this.chatInfo.sellerId,
						content: this.messageText.trim(),
						type: 'text',
						productId: this.chatInfo?.productInfo?.id || 0
					};

					// 保存当前消息内容并清空输入框
					const currentMessageText = this.messageText.trim();
					this.messageText = '';

					const res = await messageApi.send(messageData);

					if (res.statusCode === 200 && res.data.errno === 0) {
						// 构建新消息对象
						const newMessage = {
							id: res.data.data.messageId,
							content: currentMessageText,
							type: 'text',
							time: new Date().getTime(),
							isSelf: true,
							senderId: this.userInfo.id
						};

						// 添加到消息列表
						this.messageList.push(newMessage);

						// 重置页码并重新加载消息
						this.page = 1;
						await this.loadHistoryMessages();

						// 使用 nextTick 和延时双重保证滚动到底部
						this.$nextTick(() => {
							setTimeout(() => {
								this.scrollToBottom();
							}, 100);
						});

						// 更新会话列表
						await this.updateChatSession(newMessage);
					} else {
						throw new Error(res.data.errmsg || '发送失败');
					}
				} catch (error) {
					console.error('发送消息失败:', error);
					uni.showToast({
						title: error.message || '网络错误，请检查网络连接',
						icon: 'none',
						duration: 2000
					});
				}
			},
			async updateChatSession(lastMessage) {
				try {
					// 获取消息列表页面实例
					const pages = getCurrentPages();
					const messageListPage = pages.find(page => page.route === 'pages/message/messageList');

					if (messageListPage) {
						// 调用消息列表页面的更新方法
						messageListPage.$vm.updateChatSession({
							partnerId: this.chatInfo.sellerId,
							partnerName: this.chatInfo.sellerName,
							partnerAvatar: this.chatInfo.sellerAvatar,
							lastMessage: lastMessage.type === 'text' ? lastMessage.content : '[图片]',
							updateTime: lastMessage.time,
							productId: this.chatInfo.productInfo?.id
						});
					}
				} catch (error) {
					console.error('更新会话失败:', error);
				}
			},
			async chooseImage() {
				uni.chooseImage({
					count: 1,
					success: async (res) => {
						const tempFilePath = res.tempFilePaths[0];

						// 显示上传中状态
						const newMessage = {
							type: 'image',
							url: tempFilePath,
							time: new Date().getTime(),
							isSelf: true,
							status: 'uploading'
						};

						this.messageList.push(newMessage);
						this.scrollToBottom();

						try {
							const uploadRes = await messageApi.uploadImage(tempFilePath);

							if (uploadRes.statusCode === 200) {
								const uploadData = JSON.parse(uploadRes.data);
								if (uploadData.errno === 0) {
									// 发送图片消息
									const messageData = {
										toUserId: this.chatInfo.sellerId,
										content: uploadData.data.url,
										type: 'image',
										productId: this.chatInfo?.productInfo?.id || 0
									};

									const sendRes = await messageApi.send(messageData);

									if (sendRes.statusCode === 200 && sendRes.data.errno === 0) {
										newMessage.url = uploadData.data.url;
										newMessage.status = 'success';
										// 更新会话列表
										await this.updateChatSession(newMessage);
									} else {
										newMessage.status = 'failed';
									}
								} else {
									newMessage.status = 'failed';
								}
							} else {
								newMessage.status = 'failed';
							}
						} catch (error) {
							console.error('发送图片消息失败:', error);
							newMessage.status = 'failed';
						}
					}
				});
			},
			scrollToBottom() {
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.message-list').boundingClientRect(data => {
						if (data) {
							const scrollHeight = data.height + this.messageList.length * 20;
							this.scrollTop = scrollHeight;
						}
					}).exec();
				}, 300);
			},
			previewImage(url) {
				uni.previewImage({
					urls: [url],
					current: url
				});
			},
			loadMoreMessages() {
				if (this.hasMore && !this.loading) {
					this.loading = true;
					this.loadHistoryMessages().finally(() => {
						this.loading = false;
					});
				}
			},
			formatTime(timestamp) {
				if (!timestamp) return '';

				try {
					const date = new Date(timestamp);

					// 格式化为 yyyy-MM-dd HH:mm:ss
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');

					return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				} catch (error) {
					console.error('时间格式化错误:', error);
					return '';
				}
			},
			async loadChatDetail() {
				if (!this.partnerId) {
					console.error('partnerId is missing');
					return;
				}

				try {
					this.loading = true;
					const res = await messageApi.getChatDetail(this.partnerId);
					console.log('聊天详情响应:', res);

					if (res.data.errno === 0) {
						const {
							productInfo
						} = res.data.data;
						if (productInfo && !this.chatInfo.productInfo) {
							this.chatInfo.productInfo = {
								id: productInfo.id,
								name: productInfo.name,
								img: productInfo.img || '/static/default-product.png',
								price: productInfo.price
							};
						}
					}
				} catch (error) {
					console.error('加载聊天详情失败:', error);
				} finally {
					this.loading = false;
				}
			}
		}
	};
</script>

<style>
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.chat-header {
		padding: 10px;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding-top: 40px;
	}

	.back-button {
		padding: 5px 10px;
		font-size: 14px;
	}

	.chat-name {
		flex: 1;
		text-align: center;
		font-size: 16px;
		margin-right: 30px;
	}

	/* 商品卡片容器 - 固定在顶部 */
	.product-card-container {
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
		padding: 10rpx 0;
	}

	.product-card {
		display: flex;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 12rpx;
		margin: 10rpx 20rpx;
		border: 1px solid #e0e0e0;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	}

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
	}

	.product-info {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 10rpx;
	}

	.product-price {
		font-size: 32rpx;
		color: #ff6b6b;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.order-btn {
		width: 160rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		background-color: #ff6b6b;
		color: #ffffff;
		font-size: 24rpx;
		border-radius: 30rpx;
		margin-top: 10rpx;
	}

	.order-btn:active {
		opacity: 0.8;
	}

	.message-list {
		flex: 1;
		padding: 20rpx;
		background: #f5f5f5;
		height: calc(100vh - 300rpx - 180rpx); /* 减去头部、商品卡片和底部输入框的高度 */
		padding-bottom: 150rpx;
		box-sizing: border-box;
	}

	.message-item {
		display: flex;
		align-items: flex-start;
		margin: 20rpx 0;
		padding: 0 20rpx;
		width: 100%;
		box-sizing: border-box;
		position: relative;
		/* 添加相对定位 */
		z-index: 1;
		/* 确保消息在输入框下方 */
	}

	.message-self {
		flex-direction: row-reverse;
		padding-left: 20rpx;
		padding-right: 0;
	}

	.message-other {
		padding-right: 20rpx;
		padding-left: 0;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.left-avatar {
		margin-right: 20rpx;
	}

	.right-avatar {
		margin-left: 20rpx;
	}

	.message-content {
		display: flex;
		flex-direction: column;
		max-width: 60%;
		/* 减小最大宽度，避免消息太宽 */
		margin-bottom: 10rpx;
		/* 增加底部间距 */
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
		margin: 0 20rpx;
		text-align: center;
		margin-bottom: 10rpx;
	}

	.message-bubble {
		display: inline-block;
	}

	.text-message {
		display: inline-block;
		padding: 20rpx 30rpx;
		border-radius: 30rpx;
		background-color: #fff;
		font-size: 28rpx;
		line-height: 1.4;
		word-break: break-all;
		margin-bottom: 10rpx;
		/* 增加底部间距 */
	}

	.message-self .text-message {
		background-color: #95ec69;
	}

	.image-message {
		max-width: 400rpx;
		border-radius: 20rpx;
	}

	/* 调整消息对齐方式 */
	.message-self .message-content {
		align-items: flex-end;
		margin-right: 20rpx;
	}

	.message-other .message-content {
		align-items: flex-start;
		margin-left: 20rpx;
	}

	.input-area {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 100;
		/* 确保输入框在最上层 */
	}

	.input-container {
		display: flex;
		align-items: center ;
		padding: 10px 15px;
		border-top: 1px solid #eee;
		background-color: #fff;
	}

	.message-input {
		flex: 1;
		min-height: 20px;
		max-height: 120px;
		padding: 8px 12px;
		border: 1px solid #ddd;
		margin-right: 10px;
		font-size: 16px;
		line-height: 20px;
		background-color: #f8f8f8;
	}

	.button-group {
		display: flex;
		align-items: center;
	}

	.icon-button {
		padding: 8px 12px;
		margin-right: 8px;
		background: #f5f5f5;
		border-radius: 4px;
		font-size: 14px;
	}

	.send-button {
		padding: 8px 15px;
		background: #ddd;
		color: #fff;
		border-radius: 4px;
		font-size: 14px;
	}

	.send-button.active {
		background: #07c160;
	}

	.login-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.login-btn {
		margin-top: 20px;
		padding: 10px 30px;
		background-color: #07c160;
		color: #fff;
		border-radius: 4px;
		font-size: 14px;
	}
</style>